import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/filter_components/widget/advanced_filter_fuzzy_search_screen.dart';
import 'package:x3_form_core/models/advanced_filter_input_search_model.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';

import 'base_request_form_container.dart';

class BaseRequestFormBusinessInputSearchChoice extends StatefulWidget {
  final BaseHttpRequestModel request;
  final RequestSaveData requestSaveData;
  final bool isMulti;

  const BaseRequestFormBusinessInputSearchChoice({Key key, this.isMulti = false, @required this.request, @required this.requestSaveData}) : super(key: key);

  @override
  State<BaseRequestFormBusinessInputSearchChoice> createState() => _BaseRequestFormBusinessInputSearchChoiceState();
}

class _BaseRequestFormBusinessInputSearchChoiceState extends State<BaseRequestFormBusinessInputSearchChoice> {
  BaseHttpRequestModel get request => widget.request;

  BaseRequestFormProvider get baseRequestFormProvider => BaseRequestFormProvider.of(context, listen: false);

  /// 选中列表
  List<BaseKeyValueModel> selectedList = [];

  /// 选中的id - 唯一标识
  List<String> get selectedListKey => selectedList.map((e) => e.key.toString()).toList();

  List<BaseKeyValueModel> initData() {
    var data = baseRequestFormProvider.getDataSource(request);
    if (data != null) {
      if (data is List) selectedList.addAll(data.map((e) => BaseKeyValueModel.fromJson(e)).toList());
      if (data is Map) selectedList.add(BaseKeyValueModel.fromJson(data));
    }
    return [];
  }

  @override
  void initState() {
    super.initState();
    initData();
  }

  @override
  Widget build(BuildContext context) {
    return BaseRequestFormContainer(
      request: request,
      showSuffixIcon: !baseRequestFormProvider.isReadonly(request),
      onPress: onSelectData,
      suffixIcon: BaseDropDownIcon(),
      child: Container(height: 48, alignment: Alignment.centerLeft, child: request.inputType != BaseHttpInputTypeEnum.InputSearchMultipleChoice ? _buildSingleChoice() : _buildMultipleChoiceInput()),
    );
  }

  Widget _buildMultipleChoiceInput() {
    return selectedList.isEmpty
        ? Text(request.notes, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).inputDecorationTheme.hintStyle)
        : ListView.separated(
            shrinkWrap: true,
            itemCount: selectedList.length,
            scrollDirection: Axis.horizontal,
            itemBuilder: (BuildContext context, int index) {
              return Container(alignment: Alignment.center, child: Text("${selectedList[index].value}", style: Theme.of(context).textTheme.bodyText2));
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(width: 16, alignment: Alignment.center, child: Text("/"));
            },
          );
  }

  Widget _buildSingleChoice() {
    String _text = selectedList.isNotEmpty ? _showText(selectedList) : request.notes;
    return Text(_text, maxLines: 1, overflow: TextOverflow.ellipsis, style: selectedList.isNotEmpty ? Theme.of(context).textTheme.bodyText2 : Theme.of(context).inputDecorationTheme.hintStyle);
  }

  String _showText(List<BaseKeyValueModel> model) {
    String _show = "";
    model.asMap().keys.forEach((index) {
      if (model.length == 1 || index == model.length - 1) {
        _show += "${model[index].value}";
      } else {
        _show += "${model[index].value}/";
      }
    });
    return _show;
  }

  ///子页(模糊搜索弹窗页面)请求链接
  String get inputApi => getInputSearchModel().inputApi;

  ///子页面(模糊搜索弹窗页面)请求类型
  BaseHttpMethodEnum get method => getInputSearchModel().method;

  /// 子页面请求灿书
  Map<String, dynamic> get params => getInputSearchModel().params;

  ///子页面(模糊搜索弹窗页面)item
  Widget Function(Map<String, dynamic> item, bool isSelect) get childSearchItem => getChildSearchItem;

  ///子页面item唯一key
  String get childOnlyKey => getInputSearchModel().childOnlyKey;

  ///子页面item唯一value
  String get childOnlyValue => getInputSearchModel().childOnlyValue;

  String get childSearchKey => getInputSearchModel().childSearchKey;

  /// 点击选择事件
  void onSelectData() {
    BaseComponentUtils.buildDefaultBottomSheet(
      context,
      hit: "请选择",
      height: MediaQuery.of(context).size.height * 0.7,
      child: AdvancedFilterFuzzySearchScreen(
        hintText: request.notes,
        inputApi: inputApi,
        isMultipleChoice: widget.isMulti,
        completeEvent: _completeEvent,
        selectList: selectedList,
        childOnlyKey: childOnlyKey,
        childOnlyValue: childOnlyValue,
        childSearchKey: childSearchKey,
        childWidget: childSearchItem,
        method: method,
        params: params,
      ),
    );
  }

  void _completeEvent(List<BaseKeyValueModel> item) {
    selectedList.clear();
    selectedList.addAll(item);
    baseRequestFormProvider.setDataSource(request, widget.isMulti ? selectedList.map((e) => e.toBaseJson()).toList() : selectedList[0].toBaseJson());
    if (widget.requestSaveData != null) {
      widget.requestSaveData(request, {request.fieldName: baseRequestFormProvider.getDataSource(request)});
    }
    setState(() {});
  }

  /// 获取inputSearchModel
  AdvancedFilterInputSearchModel getInputSearchModel() {
    AdvancedFilterInputSearchModel inputSearchModel;
    if (request.otherParam != null && request.otherParam.containsKey("inputSearchModel")) {
      if (request.otherParam['inputSearchModel'] is AdvancedFilterInputSearchModel) {
        inputSearchModel = request.otherParam['inputSearchModel'];
      }
    }
    Map<String, dynamic> param = baseRequestFormProvider.getAllDataMapKey();
    if (inputSearchModel.params != null) {
      inputSearchModel.params = {...inputSearchModel.params, ...param};
    } else {
      inputSearchModel.params = param;
    }
    return inputSearchModel == null ? null : inputSearchModel;
  }

  /// 获取childSearchItem
  Widget getChildSearchItem(Map<String, dynamic> item, bool isSelect) {
    if (getInputSearchModel().childSearchItem == null) return defaultChildSearchItem(item, isSelect);
    Widget searchItem = getInputSearchModel().childSearchItem(item, isSelect);
    return searchItem;
  }

  Widget defaultChildSearchItem(Map<String, dynamic> item, bool isSelect) {
    String childKey = BaseUtils.getKeyData(item, childOnlyKey);
    String childValue = BaseUtils.getKeyData(item, childOnlyValue);
    TextStyle valueStyle = TextStyle(fontSize: 15, color: Color(0xFF333333));
    TextStyle keyStyle = TextStyle(fontSize: 13, color: Color(0xFF868686));
    return Container(
      height: 56,
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      color: Colors.white,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                Expanded(child: Row(children: [Text("[$childKey]", style: keyStyle), Text(childValue, style: valueStyle)])),
                Container(
                  width: 24,
                  height: 24,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(color: isSelect ? Color(0xFFFF004F) : Colors.white, shape: BoxShape.circle, border: Border.all(color: isSelect ? Color(0xFFFF004F) : Color(0xFFF3F3F3))),
                  child: Icon(BaseIconData.x3Checked, size: 16, color: isSelect ? Colors.white : Colors.transparent),
                ),
              ],
            ),
          ),
          BaseComponentUtils.buildHorizontalDivider(),
        ],
      ),
    );
  }
}
